package com.liang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liang.mall.entity.Admin;
import com.liang.mall.entity.Menu;
import com.liang.mall.entity.Role;
import com.liang.mall.myAnnotation.LogMethodInfo;
import com.liang.mapper.AdminMapper;
import com.liang.mapper.RoleMapper;
import com.liang.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lin
 * @since 2021-05-07
 */
@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService{

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    RoleMapper roleMapper;




    @LogMethodInfo(methodDesc = "登录",operation = "login")
    @Override
    public Boolean login(String username,String password) {

        HashMap<String, Object> map = new HashMap<String, Object>();

        map.put("username",username);
        map.put("password",password);

        List<Admin> admins = adminMapper.selectByMap(map);

        System.out.println("admins = " + admins);

        return !admins.isEmpty();
    }

    @Override
    public IPage<Admin> getByPage(Integer pageNum, Integer pageSize) {

        Page<Admin> page = new Page<>(pageNum,pageSize);

        IPage<Admin> adminIPage = adminMapper.selectPage(page, null);


        return adminIPage;
    }

    @Override
    public IPage<Admin> queryByName(Integer pageNum, Integer pageSize, String username) {

        Page<Admin> adminPage = new Page<>(pageNum, pageSize);

        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("username",username);

        IPage<Admin> adminIPage = adminMapper.selectPage(adminPage, queryWrapper);

        return adminIPage;
    }


    /**
     * 安全框架 security 用户校验
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 获取验证码, 检验
        log.info("认证需要的用户名: {}",username);
        // 查询数据库,完成用户名的校验
        Admin admin = adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username));
        if (null == admin) {
            throw new RuntimeException(username+"不存在");
        }
        log.info("查询结果: {}",admin);
//         根据用ID查询
        List<Role> doList = roleMapper.selectListRole(admin.getId());


//         拼接 ROLE_ 字符
        List<String> roleNames = doList.stream().map(roleDO -> "ROLE_" + roleDO.getRoleName()).collect(Collectors.toList());

       String[] roles =  new String[roleNames.size()];

        for (int i = 0; i < roleNames.size(); i++) {
            roles[i] = roleNames.get(i);
            System.out.println(roleNames.get(i));
        }

        List<Menu>  menuList = roleMapper.selectListPerms(admin.getId());

        System.out.println(menuList);
//        List<String[]> perms = menuList.stream().filter(menu -> !menu.getPerms().isEmpty()).map(menu -> menu.getPerms().split(",")).collect(Collectors.toList());



//        ArrayList<String> strings = new ArrayList<>();
        StringBuilder stringBuilder = new StringBuilder();
//
        for (Menu menu : menuList) {

            if (menu.getPerms()==null){
                continue;
            }

            stringBuilder.append(menu.getPerms()).append(",");


        }

        String s = stringBuilder.toString();

        String[] perms = s.split(",");


        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

        return new User(admin.getUsername(),encoder.encode(admin.getPassword()), AuthorityUtils.createAuthorityList(perms));


    }
}
